package com.yiwei.hdb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.hdb.R;
import com.yiwei.hdb.api.Api;
import com.yiwei.hdb.api.bean.ModifyIdcardBean;
import com.yiwei.hdb.api.bean.UploadImageBean;
import com.yiwei.hdb.constant.Const;
import com.yiwei.hdb.constant.FaceBitmap;
import com.yiwei.hdb.constant.IdCardBitmap;
import com.yiwei.hdb.util.ImageUtil;
import com.yiwei.hdb.util.Network;
import com.yiwei.hdb.util.RxLifeUtil;
import com.yiwei.hdb.util.ToastUtil;
import com.yiwei.hdb.util.Util;
import com.yiwei.hdb.view.CircularProgress;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-11-22.
 */

public class ChangePhoneIdcardActivity extends BaseActivity {

    @BindView(R.id.img_front)
    ImageView frontIv;
    //    @BindView(R.id.take1)
//    ImageView take1;
    @BindView(R.id.img_back)
    ImageView backIv;
    //    @BindView(R.id.take2)
//    ImageView take2;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.progressBar)
    CircularProgress loading;
    private Unbinder unbinder;
    private int type;
    private int btnId;
    private static final String DEFAULT_NAME1 = "front_image.jpg";
    private static final String DEFAULT_NAME2 = "back_image.jpg";
    private boolean isTakeOne;
    private boolean isTakeTwo;
    private String frontUrl = "";
    private String backUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.activity_identity_by_people_one);
        baseInitView(this, "ChangePhoneIdcardActivity", Const.ViewType.ACTIVITY);
        unbinder = ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (IdCardBitmap.bitmap != null && !IdCardBitmap.bitmap.isRecycled()) {
            IdCardBitmap.bitmap.recycle();
            IdCardBitmap.bitmap = null;
        }
        unbinder.unbind();
    }

    private void initView() {
        setBackIntent();
        setTitleText("人工认证");

    }

    private void showLoading(boolean b) {
        if (loading != null) {
            if (b)
                loading.setVisibility(View.VISIBLE);
            else
                loading.setVisibility(View.GONE);
        }
    }

    private void checkCameraPermission(final int type) {

        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                if (type == 1) {
                    btnId = 1;
                    startActivity(DEFAULT_NAME1);
                } else if (type == 2) {
                    btnId = 2;
                    startActivity(DEFAULT_NAME2);
                }
            }

            @Override
            public void superReject() {

            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    private void startActivity(String paramString) {
        Intent localIntent = new Intent(this, CameraActivity.class);
        localIntent.putExtra("path", "/sdcard/pictures");
        localIntent.putExtra("name", paramString);
        localIntent.putExtra("type", "idcard");
        startActivityForResult(localIntent, 100);
    }

    public void uploadImg(String img) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        showLoading(true);
        UploadImageBean bean = new UploadImageBean();
        bean.img = img;
        Api.api_service.uploadImg(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        showLoading(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (type == 1) {
                        frontUrl = result.getUrl();
                    } else if (type == 2) {
                        backUrl = result.getUrl();
                    }
                    if (isTakeOne && isTakeTwo) {
                        btnSubmit.setSelected(true);
                    } else {
                        btnSubmit.setSelected(false);
                    }
                });
    }

    public void uploadAll(String frontIv, String backIv) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        showLoading(true);
        ModifyIdcardBean bean = new ModifyIdcardBean();
        bean.idcard_front = frontIv;
        bean.idcard_back = backIv;
        Api.api_service.getModifyIdcard(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        showLoading(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(getApplicationContext(), "身份认证成功", Toast.LENGTH_SHORT);
                    Util.startActivity(this, ChangePhoneFaceActivity.class);
                    finish();
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == -1) {
                try {

                    if (btnId == 1) {
                        isTakeOne = true;
//                        take1.setVisibility(View.GONE);
                        if (IdCardBitmap.bitmap != null) {
                            frontIv.setImageBitmap(IdCardBitmap.bitmap);
                            uploadImg(ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap));
                        }

                    } else if (btnId == 2) {
                        isTakeTwo = true;
//                        take2.setVisibility(View.GONE);
                        if (IdCardBitmap.bitmap != null) {
                            backIv.setImageBitmap(IdCardBitmap.bitmap);
                            uploadImg(ImageUtil.Bitmap2StrByBase64(IdCardBitmap.bitmap));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private boolean checkPhoto() {
        if (!this.isTakeOne) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.photo_one_is_empty), 0);
            return false;
        }
        if (!this.isTakeTwo) {
            ToastUtil.makeText(getApplicationContext(), getResources().getString(R.string.photo_two_is_empty), 0);
            return false;
        }
        return true;
    }

    @OnClick({R.id.img_front, R.id.img_back, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_front:
                type = 1;
                checkCameraPermission(1);
                break;
            case R.id.img_back:
                type = 2;
                checkCameraPermission(2);
                break;
            case R.id.btn_submit:
                if (checkPhoto())
                    uploadAll(frontUrl, backUrl);
                break;
        }
    }
}
